package filter;

import pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 登录验证的过滤器
 */
@WebFilter(value = "/*", dispatcherTypes = {DispatcherType.FORWARD, DispatcherType.REQUEST})
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String uri = request.getRequestURI();
        //System.out.println(uri);
        if (uri.contains("login.jsp") || uri.contains("checkCode.jpg") || uri.contains("userServlet") || uri.contains("index.jsp")) {
            //System.out.println("come....");
            filterChain.doFilter(req, resp);
        } else {
            //System.out.println("get...");
            User userLogin = (User) request.getSession().getAttribute("userLogin");
            //System.out.println(userLogin);
            if (userLogin != null) {
                //System.out.println("not null");
                filterChain.doFilter(req, resp);
            } else {
                //System.out.println("null");
                request.setAttribute("tips", "您尚未登录，请登录");
                request.getRequestDispatcher("/login.jsp").forward(request, resp);
            }
        }
    }

    @Override
    public void destroy() {
        //Filter.super.destroy();
    }
}
